<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="系统列表" prop="roleName" label-width="120px">
          <el-select v-model="value" placeholder="无登录系统" size="large" suffix-icon="Switch" style="width: 260px" @change="changeValue">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <div>
            <el-form-item label="菜单名称" prop="reName" label-width="120px">
               <el-input
                  v-model="queryParams.reName"
                  placeholder="请输入菜单名称"
                  clearable
                   style="width: 260px"
                  @keyup.enter="handleQuery"
                  @clear="handleQuery"
                  @input="handleInput"
               />
            </el-form-item>
            <el-form-item>
               <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>

            </el-form-item>
        </div>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button 
               type="info"
               plain
               icon="Sort"
               @click="toggleExpandAll"
            >展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
         v-if="refreshTable"
         v-loading="loading"
         :data="menuList"
         row-key="id"
         :indent="30"
         :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
         <el-table-column prop="reName" label="菜单名称" :show-overflow-tooltip="true" align="left" width="200"></el-table-column>
         <el-table-column prop="reIcon" label="图标" align="center" width="100">
            <template #default="scope">
               <svg-icon :icon-class="scope.row.reIcon" />
            </template>
         </el-table-column>
         <!-- <el-table-column prop="reOrder" label="排序" align="center" width="100"></el-table-column> -->
         <el-table-column prop="rePath" label="路由地址" align="center"></el-table-column>
         <el-table-column prop="reValue" label="组件地址" align="center"></el-table-column>
         <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" >新增</el-button>
               <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="title" v-model="open" width="680px" append-to-body>
         <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
               <el-col :span="24">
                  <el-form-item label="上级菜单">
                     <el-tree-select
                        v-model="form.reParetntID"
                        :data="menuOptions"
                        :props="{ value: 'menuId', label: 'reName', children: 'children' }"
                        value-key="menuId"
                        placeholder="选择上级菜单"
                        check-strictly
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="菜单图标" prop="reIcon">
                     <el-popover
                        placement="bottom-start"
                        :width="540"
                        trigger="click"
                     >
                        <template #reference>
                           <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                              <template #prefix>
                                 <svg-icon
                                    v-if="form.reIcon"
                                    :icon-class="form.reIcon"
                                    class="el-input__icon"
                                    style="height: 32px;width: 16px;"
                                 />
                                 <el-icon v-else style="height: 32px;width: 16px;"><search /></el-icon>
                              </template>
                           </el-input>
                        </template>
                        <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.reIcon" />
                     </el-popover>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="reOrder">
                     <el-input-number v-model="form.reOrder" controls-position="right" :min="1" :max="100" @change="handleChange" @blur="handleChange"/>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="菜单名称" prop="reName">
                     <el-input v-model="form.reName" placeholder="请输入菜单名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item prop="rePath">
                     <template #label>
                        <span>
                           <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           路由地址
                        </span>
                     </template>
                     <el-input v-model="form.rePath" placeholder="请输入路由地址" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-col :span="12" v-if="form.reParetntID!=0">
                  <el-form-item prop="reValue">
                     <template #label>
                        <span>
                           <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           组件路径
                        </span>
                     </template>
                     <el-input v-model="form.reValue" placeholder="请输入组件路径" />
                  </el-form-item>
               </el-col>
             <el-form-item label="资源描述" :required="false" prop="reDes">
               <el-input v-model="form.reDes" type="textarea" placeholder="请输入资源描述" maxlength="100"></el-input>
            </el-form-item>
            <!-- <el-form-item label="禁用状态" label-width="100">
               <el-radio-group v-model="form.status">
                  <el-radio :value="0">禁用</el-radio>
                  <el-radio :value="1">启用</el-radio>
               </el-radio-group>
            </el-form-item> -->
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu">
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";

const { proxy } = getCurrentInstance();
// const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");

const menuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const iconSelectRef = ref(null);
const value = ref('')
const options = ref([])


const data = reactive({
  form: {},
  queryParams: {
    reName: "",
  },
  rules: {
    reName: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    reOrder: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
    rePath: [{ required: true, message: "路由地址不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

// 切换系统
function changeValue(val){
  value.value = val;
  queryParams.value.tenantID = val;
  getList();
} 


/** 查询菜单列表 */
async function getList() {
  loading.value = true;
// 先查询系统列表
  const data = await proxy.API.GetTenantList({tenantname:null});
  if(data.code===1 && data?.data?.length>0){
    options.value = data.data.map(item => {
      return { value: item.id, label: item.tenantName }
    })
    // 默认选择第一个系统
    value.value = value.value?value.value:options.value[0].value;
    queryParams.value.tenantID = queryParams.value.tenantID?queryParams.value.tenantID:options.value[0].value;
    proxy.API.GetResourceList({
      reName: queryParams.value.reName,
      rePath: "",
      reParetntID: -1,//查询全部路由
      tenantID: value.value
    }).then(response => {
         response.data.forEach(element => {
            element.children = [];
         });
        menuList.value = proxy.handleTree(response.data);
        loading.value = false;
    });
  }else{
     loading.value = false;
     proxy.$modal.msgError("当前还没有系统，请先添加系统");
  }
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
   proxy.API.GetResourceList({
      reName: queryParams.value.reName,
      rePath: "",
      reParetntID: -1,//查询全部路由
      tenantID: value.value
    }).then(response => {
      response.data.forEach(element => {
         element.children = [],
         element.parentId = element.reParetntID,
         element.menuId = element.id
      });

       const menu = { menuId: 0, reName: "主类目", children: [] };
       menu.children = proxy.handleTree(response.data, "menuId");
      
       menuOptions.value.push(menu);

    });
}

// 处理值变化的方法
const handleChange = (value) => {
  if (Number.isInteger(value)) {
    if (value < 0) {
      form.value.reOrder = 1;
    } else if (value > 100) {
      form.value.reOrder = 100;
    }
  } else {
    // 如果不是整数，恢复到上一个有效值
    form.value.reOrder = Math.round(form.value.reOrder);
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: "",
    reDes: "",
    reParetntID: 0,
    reName: "",
    reIcon: "",
    reOrder: 1,
    rePath: "",
    reValue: "",
    status: 1,
  };
  proxy.resetForm("menuRef");
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}

/** 选择图标 */
function selected(name) {
  form.value.reIcon = name;
}

// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
    clearTimeout(timer);
    timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.reParetntID = row.id;
  } else {
    form.value.reParetntID = 0;
  }
  open.value = true;
  title.value = "添加菜单";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  Object.keys(form.value).forEach(key => {
    form.value[key] = row[key];
  });
  open.value = true;
  title.value = "修改菜单";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate(valid => {
    if (valid) {
      if (form.value.id != "") {
         proxy.API.EditResource({
            ...form.value,
            tenantID:value.value,
            reClass: value.value+'_'+form.value.rePath,
            reRights:[0,1,2,3,4,5,6,7,8,9],
         }).then(response => {
            proxy.$modal.msgSuccess("编辑成功");
            open.value = false;
            getList();
         });
      } else {
         proxy.API.AddResource({
            ...form.value,
            tenantID:value.value,
            reClass: value.value+'_'+form.value.rePath,
            reRights:[0,1,2,3,4,5,6,7,8,9],
         }).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
         });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除菜单"' + row.reName + '"的数据项?').then(function () {
    proxy.API.DelResource({id:row.id}).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

getList();

</script>

<style lang="scss" scoped>
::v-deep(.el-select__icon){
   color: #409EFF;
 }
</style>
